package ym.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ym.exception.MyException;
import ym.mapper.UserMapper;
import ym.pojo.User;
import ym.service.UserService;
import ym.utils.JWTUtil;
import ym.utils.Md5Util;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void add(User user) {
        user.setPassword(Md5Util.encode(user.getPassword()));
        userMapper.insert(user);
    }

    @Override
    public void update(User user) {
        User userFromData = userMapper.selectById(user.getUserId());
        //判断密码是否修改[若密码为空或者密码和数据库中相等，则未修改]
        if (user.getPassword().equals(userFromData.getPassword())) {
            userMapper.updateById(user);
        } else {
            //若修改，则加密后在保存
            user.setPassword(Md5Util.encode(user.getPassword()));
            userMapper.updateById(user);
        }
    }

    @Override
    public void delete(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public Page<User> search(int page, int size) {
        return userMapper.selectPage(new Page<>(page, size), null);
    }

    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public void updateStatus(Integer id) {
        User user = userMapper.selectById(id);
        if (user.getUserStatus().equals("1")) {
            user.setUserStatus("0");
            userMapper.updateById(user);
        } else {
            user.setUserStatus("1");
            userMapper.updateById(user);
        }
    }

    @Override
    public void saveRegisterCheckCode(String phone, String checkCode) {
        //向redis缓存注册验证码，手机验证码过期时间设为5分钟
        redisTemplate.opsForValue().set("registerCheckCode" + phone, checkCode, 300, TimeUnit.SECONDS);
    }

    @Override
    public void registerCheckCode(String phone, String checkCode) {
        //获取redis中缓存的注册验证码
        String checkCodeFromRedis = (String) redisTemplate.opsForValue().get("registerCheckCode" + phone);
        if (!checkCodeFromRedis.equals(checkCode)) {
            throw new MyException(604, "验证码错误");
        }
    }

    @Override
    public void register(User user) {
        //验证手机号是否存在
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("phone", user.getPhone());
        List<User> users1 = userMapper.selectList(queryWrapper1);
        if (users1 != null && users1.size() > 0) {
            throw new MyException(604, "手机号已存在");
        }
        //验证账号是否存在
        QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("username", user.getPhone());
        List<User> users2 = userMapper.selectList(queryWrapper2);
        if (users2 != null && users2.size() > 0) {
            throw new MyException(604, "账号已存在");
        }
        //激活用户
        user.setUserStatus("1");
        //加密密码
        user.setPassword(Md5Util.encode(user.getPassword()));
        //新增用户
        userMapper.insert(user);
    }

    @Override
    public String loginPassword(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        //判断用户是否存在
        if (user == null) {
            throw new MyException(605, "用户不存在");
        }
        //判断面是否正确
        boolean verify = Md5Util.verify(password, user.getPassword());
        if (!verify) {
            throw new MyException(605, "密码错误");
        }
        //登录成功，生成jwt令牌
        String token = JWTUtil.token(user);
        return token;
    }

    @Override
    public void saveLoginCheckCode(String phone, String checkCode) {
        //判断该手机号是否有对应的用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            //向redis缓存登录验证码，手机验证码过期时间设为5分钟
            redisTemplate.opsForValue().set("loginCheckCode" + phone, checkCode, 300, TimeUnit.SECONDS);
        } else {
            throw new MyException(605, "用户不存在");
        }

    }

    @Override
    public String loginCheckCode(String phone, String checkCode) {
        //获取redis中缓存的登录验证码
        String checkCodeFromRedis = (String) redisTemplate.opsForValue().get("loginCheckCode" + phone);
        if (!checkCodeFromRedis.equals(checkCode)) {
            throw new MyException(604, "验证码错误");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        User user = userMapper.selectOne(queryWrapper);
        //登录成功，生成jwt令牌
        return JWTUtil.token(user);
    }

    @Override
    public User getLoginUser(String token) {
        return userMapper.selectById(JWTUtil.verifyAndGetId(token));
    }
}
